<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<!DOCTYPE html>
<html>
<head>
    <title>购物车 - 助农购物网站</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="icon" type="image/x-icon" href="${pageContext.request.contextPath}/logo/favicon.ico">
    <link href="${pageContext.request.contextPath}/css/bootstrap.min.css" rel="stylesheet">
    <style>
        .cart-item {
            border: 1px solid #dee2e6;
            border-radius: 5px;
            padding: 15px;
            margin-bottom: 15px;
        }
        .cart-item-image {
            width: 100px;
            height: 100px;
            object-fit: cover;
            border-radius: 5px;
        }
        .quantity-input {
            width: 80px;
            text-align: center;
        }
        .total-section {
            background-color: #f8f9fa;
            padding: 20px;
            border-radius: 5px;
            margin-top: 20px;
        }
        .payment-card {
            transition: all 0.3s;
        }
        .payment-card:hover {
            border-color: #0d6efd !important;
            box-shadow: 0 0 5px rgba(13, 110, 253, 0.3);
        }
        .payment-card.selected {
            border-color: #0d6efd !important;
            background-color: #e7f1ff;
        }
    </style>
</head>
<body>
    <jsp:include page="../common/header.jsp"/>
    
    <div class="container mt-4">
        <h2>我的购物车</h2>
        
        <c:if test="${error != null}">
            <div class="alert alert-danger">${error}</div>
        </c:if>
        
        <c:choose>
            <c:when test="${cartList != null && !empty cartList}">
                <form id="checkoutForm">
                    <div class="mb-3">
                        <label>
                            <input type="checkbox" id="selectAll" onchange="toggleSelectAll()"> 全选
                        </label>
                    </div>
                    
                    <div id="cartItems">
                        <c:forEach var="cart" items="${cartList}">
                            <div class="cart-item">
                                <div class="row align-items-center">
                                    <div class="col-md-1">
                                        <input type="checkbox" class="cart-checkbox" value="${cart.cartId}" 
                                               onchange="updateTotal()">
                                    </div>
                                    <div class="col-md-2">
                                        <c:if test="${cart.product.imageUrl != null && !empty cart.product.imageUrl}">
                                            <img src="${cart.product.imageUrl}" class="cart-item-image" alt="${cart.product.productName}">
                                        </c:if>
                                    </div>
                                    <div class="col-md-4">
                                        <h5>${cart.product.productName}</h5>
                                        <p class="text-muted mb-0">分类：${cart.product.category}</p>
                                        <p class="text-danger mb-0">单价：¥<fmt:formatNumber value="${cart.product.price}" pattern="#,##0.00"/></p>
                                    </div>
                                    <div class="col-md-2">
                                        <div class="input-group">
                                            <button class="btn btn-outline-secondary" type="button" 
                                                    onclick="updateQuantity(${cart.cartId}, -1)">-</button>
                                            <input type="number" class="form-control quantity-input" 
                                                   id="quantity_${cart.cartId}" 
                                                   value="${cart.quantity}" 
                                                   min="1" 
                                                   max="${cart.product.stock}"
                                                   onchange="updateCartQuantity(${cart.cartId})">
                                            <button class="btn btn-outline-secondary" type="button" 
                                                    onclick="updateQuantity(${cart.cartId}, 1)">+</button>
                                        </div>
                                        <small class="text-muted">库存：${cart.product.stock}</small>
                                    </div>
                                    <div class="col-md-2">
                                        <p class="mb-0"><strong>小计：¥<span id="subtotal_${cart.cartId}">
                                            <fmt:formatNumber value="${cart.product.price * cart.quantity}" pattern="#,##0.00"/>
                                        </span></strong></p>
                                    </div>
                                    <div class="col-md-1">
                                        <button type="button" class="btn btn-danger btn-sm" 
                                                onclick="deleteCartItem(${cart.cartId})">删除</button>
                                    </div>
                                </div>
                            </div>
                        </c:forEach>
                    </div>
                    
                    <div class="total-section">
                        <div class="row">
                            <div class="col-md-8">
                                <h5>收货信息</h5>
                                <div class="mb-2">
                                    <label class="form-label">收货地址：</label>
                                    <input type="text" class="form-control" id="deliveryAddress" 
                                           value="${sessionScope.user.address != null ? sessionScope.user.address : ''}" 
                                           required>
                                </div>
                                <div class="row">
                                    <div class="col-md-6 mb-2">
                                        <label class="form-label">收货人：</label>
                                        <input type="text" class="form-control" id="receiverName" 
                                               value="${sessionScope.user.realName != null ? sessionScope.user.realName : ''}" 
                                               required>
                                    </div>
                                    <div class="col-md-6 mb-2">
                                        <label class="form-label">联系电话：</label>
                                        <input type="text" class="form-control" id="receiverPhone" 
                                               value="${sessionScope.user.phone != null ? sessionScope.user.phone : ''}" 
                                               required>
                                    </div>
                                </div>
                                <div class="mb-3 mt-3">
                                    <label class="form-label">支付方式：</label>
                                    <div class="row">
                                        <div class="col-md-6">
                                            <div class="card payment-card" style="cursor: pointer; border: 2px solid #dee2e6;" onclick="selectPayment('支付宝')">
                                                <div class="card-body text-center">
                                                    <input type="radio" name="paymentMethod" value="支付宝" id="paymentAlipay" checked style="display: none;">
                                                    <h6 class="mb-0">支付宝</h6>
                                                    <small class="text-muted">余额支付</small>
                                                </div>
                                            </div>
                                        </div>
                                        <div class="col-md-6">
                                            <div class="card payment-card" style="cursor: pointer; border: 2px solid #dee2e6;" onclick="selectPayment('微信支付')">
                                                <div class="card-body text-center">
                                                    <input type="radio" name="paymentMethod" value="微信支付" id="paymentWechat" style="display: none;">
                                                    <h6 class="mb-0">微信支付</h6>
                                                    <small class="text-muted">余额支付</small>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <div class="col-md-4 text-end">
                                <p>已选商品：<span id="selectedCount">0</span> 件</p>
                                <h4>合计：¥<span id="totalAmount">0.00</span></h4>
                                <button type="button" class="btn btn-primary btn-lg w-100" 
                                        onclick="checkout()">结算</button>
                            </div>
                        </div>
                    </div>
                </form>
            </c:when>
            <c:otherwise>
                <div class="alert alert-info text-center">
                    <h5>购物车是空的</h5>
                    <p>快去挑选心仪的商品吧！</p>
                    <a href="${pageContext.request.contextPath}/client/index" class="btn btn-primary">去购物</a>
                </div>
            </c:otherwise>
        </c:choose>
    </div>
    
    <script src="${pageContext.request.contextPath}/js/bootstrap.bundle.min.js"></script>
    <script>
        // 初始化总价
        updateTotal();
        
        // 全选/取消全选
        function toggleSelectAll() {
            const selectAll = document.getElementById('selectAll');
            const checkboxes = document.querySelectorAll('.cart-checkbox');
            checkboxes.forEach(checkbox => {
                checkbox.checked = selectAll.checked;
            });
            updateTotal();
        }
        
        // 更新总价
        function updateTotal() {
            const checkboxes = document.querySelectorAll('.cart-checkbox:checked');
            let total = 0;
            let count = 0;
            
            checkboxes.forEach(checkbox => {
                const cartId = checkbox.value;
                const quantity = parseInt(document.getElementById('quantity_' + cartId).value);
                const price = parseFloat(document.getElementById('subtotal_' + cartId).textContent.replace(/,/g, ''));
                total += price;
                count += quantity;
            });
            
            document.getElementById('selectedCount').textContent = count;
            document.getElementById('totalAmount').textContent = total.toFixed(2).replace(/\B(?=(\d{3})+(?!\d))/g, ",");
        }
        
        // 更新数量（按钮）
        function updateQuantity(cartId, delta) {
            const input = document.getElementById('quantity_' + cartId);
            let quantity = parseInt(input.value) + delta;
            const max = parseInt(input.max);
            const min = parseInt(input.min);
            
            if (quantity < min) quantity = min;
            if (quantity > max) quantity = max;
            
            input.value = quantity;
            updateCartQuantity(cartId);
        }
        
        // 更新购物车数量（AJAX）
        function updateCartQuantity(cartId) {
            const input = document.getElementById('quantity_' + cartId);
            const quantity = parseInt(input.value);
            
            if (quantity <= 0) {
                alert('数量必须大于0');
                location.reload();
                return;
            }
            
            const params = new URLSearchParams();
            params.append('cartId', cartId);
            params.append('quantity', quantity);
            
            fetch('${pageContext.request.contextPath}/client/cart?action=update', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
                },
                body: params.toString()
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    // 重新计算小计
                    const cartItem = document.querySelector('[id="quantity_' + cartId + '"]').closest('.cart-item');
                    const priceText = cartItem.querySelector('.text-danger').textContent;
                    const price = parseFloat(priceText.match(/[\d.]+/)[0]);
                    const subtotal = price * quantity;
                    document.getElementById('subtotal_' + cartId).textContent = subtotal.toFixed(2).replace(/\B(?=(\d{3})+(?!\d))/g, ",");
                    updateTotal();
                } else {
                    alert(data.message || '更新失败');
                    location.reload();
                }
            })
            .catch(error => {
                console.error('Error:', error);
                alert('更新失败，请重试');
                location.reload();
            });
        }
        
        // 删除购物车项
        function deleteCartItem(cartId) {
            if (!confirm('确定要删除这个商品吗？')) {
                return;
            }
            
            const params = new URLSearchParams();
            params.append('cartId', cartId);
            
            fetch('${pageContext.request.contextPath}/client/cart?action=delete', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
                },
                body: params.toString()
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    location.reload();
                } else {
                    alert(data.message || '删除失败');
                }
            })
            .catch(error => {
                console.error('Error:', error);
                alert('删除失败，请重试');
            });
        }
        
        // 选择支付方式
        function selectPayment(method) {
            // 移除所有选中状态
            document.querySelectorAll('.payment-card').forEach(card => {
                card.classList.remove('selected');
            });
            // 设置选中的支付方式
            document.querySelectorAll('input[name="paymentMethod"]').forEach(radio => {
                radio.checked = false;
            });
            if (method === '支付宝') {
                document.getElementById('paymentAlipay').checked = true;
                document.querySelectorAll('.payment-card')[0].classList.add('selected');
            } else {
                document.getElementById('paymentWechat').checked = true;
                document.querySelectorAll('.payment-card')[1].classList.add('selected');
            }
        }
        
        // 初始化支付方式选择
        document.addEventListener('DOMContentLoaded', function() {
            selectPayment('支付宝');
        });
        
        // 结算
        function checkout() {
            const checkboxes = document.querySelectorAll('.cart-checkbox:checked');
            if (checkboxes.length === 0) {
                alert('请选择要结算的商品');
                return;
            }
            
            const cartIds = Array.from(checkboxes).map(cb => cb.value);
            const deliveryAddress = document.getElementById('deliveryAddress').value.trim();
            const receiverName = document.getElementById('receiverName').value.trim();
            const receiverPhone = document.getElementById('receiverPhone').value.trim();
            const paymentMethodInput = document.querySelector('input[name="paymentMethod"]:checked');
            
            if (!deliveryAddress || !receiverName || !receiverPhone) {
                alert('请填写完整的收货信息');
                return;
            }
            
            if (!paymentMethodInput) {
                alert('请选择支付方式');
                return;
            }
            
            if (!confirm('确定要结算选中的商品吗？')) {
                return;
            }
            
            const params = new URLSearchParams();
            cartIds.forEach(id => {
                params.append('cartIds[]', id);
            });
            params.append('deliveryAddress', deliveryAddress);
            params.append('receiverName', receiverName);
            params.append('receiverPhone', receiverPhone);
            params.append('paymentMethod', paymentMethodInput.value);
            
            const checkoutBtn = event.target;
            checkoutBtn.disabled = true;
            checkoutBtn.textContent = '结算中...';
            
            fetch('${pageContext.request.contextPath}/client/cart?action=checkout', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
                },
                body: params.toString()
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    alert('结算成功！');
                    window.location.href = '${pageContext.request.contextPath}/client/order?action=list';
                } else {
                    alert(data.message || '结算失败');
                    checkoutBtn.disabled = false;
                    checkoutBtn.textContent = '结算';
                }
            })
            .catch(error => {
                console.error('Error:', error);
                alert('结算失败，请重试');
                checkoutBtn.disabled = false;
                checkoutBtn.textContent = '结算';
            });
        }
    </script>
</body>
</html>

